package com.zpy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zpy.pojo.*;
import com.zpy.service.BookService;
import com.zpy.service.UnitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
@Slf4j
@Controller
@RequestMapping("book")
public class BookController {
    @Autowired
    private BookService bookService;
    @Autowired
    private UnitService unitService;
    @Value("${location}")
    private String location;
    @RequestMapping("listBook")
    public String listBook(@RequestParam(required = false,value ="pageNum",defaultValue = "1")Integer pageNum,
                           @RequestParam(required = false,value ="pageSize",defaultValue = "10")Integer pageSize, Model model, Book book){

        if (pageNum<0 || pageNum.equals("") || pageNum==null){
            pageNum=1;
        }
        if (pageSize<0 || pageSize.equals("") || pageSize==null){
            pageSize=10;
        }
        PageHelper.startPage(pageNum,pageSize);
        QueryWrapper<Book> qw=new QueryWrapper<>();
        if (book.getBname()!=null){
            qw.like("bname",book.getBname());
        }
        qw.orderByAsc("status");
        List<Book> list = bookService.list(qw);
        PageInfo<Book> pageInfo = new PageInfo<>(list);
        model.addAttribute("pageInfo",pageInfo);
        return "book-list";

    }

    //跳转到修改图书的页面
    @RequestMapping("preUpdateBook/{id}")
    public String preUpdateReader(@PathVariable Integer id, Model model){

        Book book = bookService.getById(id);
        model.addAttribute("book",book);
        return "book-update";
    }

    //修改图书
    @RequestMapping("updateBook")
    public String updateReader(Book book){
        boolean b = bookService.updateById(book);
        return "redirect:/book/listBook";
    }
    //删除图书
    @RequestMapping("delBook/{id}")
    public String delReader(@PathVariable Integer id){
        boolean b = bookService.removeById(id);
        return "redirect:/book/listBook";
    }
    //详情
    @RequestMapping("detail/{id}")
    public String detail(@PathVariable Integer id,Model model){
        Book byId = bookService.getById(id);
        model.addAttribute("book",byId);
        return "book-detail";
    }



    //图书入库（工作人员）
    @RequestMapping("preSaveBook")
    public String preSaveBook(Model model,HttpSession session){
        QueryWrapper<Book>qw=new QueryWrapper<>();
        String unit = (String) session.getAttribute("unit");
        model.addAttribute("unit",unit);
        return "worker-book-save";
    }

    //添加图书（工作人员）
    @RequestMapping("saveBook")
    public String saveBook(Book book, MultipartFile file){
        transFile(book,file);//调用自己写的方法
        boolean save = bookService.save(book);//调用mybatis-plus的save添加方法方法
        return "redirect:/book/listWorkerBook";//重定向
    }

    private void transFile(Book book, MultipartFile file) {//这个file就是在前端选择的文件
        String originalFilename = file.getOriginalFilename();//获得文件全名
        int index = originalFilename.lastIndexOf(".");//将文件名前后分开
        String suffix = originalFilename.substring(index);//构造后缀
        String prefix =System.nanoTime()+"";//构造前缀
        String path=prefix+suffix;//拼接成文件名
        File file1 = new File(location);//new 一个要下载的路径的file对象
        if (!file1.exists()){//如果电脑上不存在这个目录
            file1.mkdirs();//创建这个目录
        }
        File file2 = new File(file1,path);
        try {
            file.transferTo(file2);//调用上传方法
        } catch (IOException e) {
            e.printStackTrace();
        }
        book.setBimage(path);
    }



    //查看所有图书-这个查看是不管你的图书开不开放，图书管理只能管理本本单位的，即使其他单位的图书开放，这里也是看不到的，开放只涉及流通和借阅的时候可以被其他单位的用户看到（工作人员）
    @RequestMapping("listWorkerBook")
    public String listWorkerBook(@RequestParam(required = false,value ="pageNum",defaultValue = "1")Integer pageNum,
                                 @RequestParam(required = false,value ="pageSize",defaultValue = "10")Integer pageSize,
                                 Model model, Book book, HttpSession session){

        if (pageNum<0 || pageNum.equals("") || pageNum==null){
            pageNum=1;
        }
        if (pageSize<0 || pageSize.equals("") || pageSize==null){
            pageSize=10;
        }
        PageHelper.startPage(pageNum,pageSize);
        QueryWrapper<Book> qw=new QueryWrapper<>();
        if (book.getBname()!=null){
            qw.like("bname",book.getBname());

        }
        if (book.getId()!=null){
            qw.like("id",book.getId());
        }
        if (book.getPress()!=null){
            qw.like("press",book.getPress());
        }
        if (book.getAuthor()!=null){
            qw.like("author",book.getAuthor());
        }
        String unit = (String) session.getAttribute("unit");
        qw.eq("unit",unit);
        qw.orderByAsc("status");
        List<Book> list = bookService.list(qw);
        PageInfo<Book> pageInfo = new PageInfo<>(list);
        model.addAttribute("pageInfo",pageInfo);
        return "worker-book-list";

    }

    //详情（工作人员）
    @RequestMapping("bookDetail/{id}")
    public String bookDetail(@PathVariable Integer id,Model model){
        Book byId = bookService.getById(id);
        model.addAttribute("book",byId);
        return "worker-book-detail";
    }

    //删除图书（工作人员）
    @RequestMapping("delWorkerBook/{id}")
    public String delWorkerBook(@PathVariable Integer id){
        boolean b = bookService.removeById(id);
        return "redirect:/book/listWorkerBook";
    }

    //跳转到修改图书的页面（工作人员）
    @RequestMapping("preUpdateWorkerBook/{id}")
    public String preUpdateWorkerBook(@PathVariable Integer id, Model model){

        Book book = bookService.getById(id);
        model.addAttribute("book",book);
        return "worker-book-update";
    }

    //修改图书（工作人员）
    @RequestMapping("updateWorkerBook")
    public String updateWorkerBook(Book book){
        boolean b = bookService.updateById(book);
        return "redirect:/book/listWorkerBook";
    }
    //开放（工作人员）
    @RequestMapping("open/{id}")
    public String open(@PathVariable Integer id){
        Book byId = bookService.getById(id);
        byId.setIsopen(1);
        boolean b = bookService.updateById(byId);
        return "redirect:/book/listWorkerBook";
    }
    //隐藏（工作人员）
    @RequestMapping("close/{id}")
    public String close(@PathVariable Integer id){
        Book byId = bookService.getById(id);
        byId.setIsopen(0);
        boolean b = bookService.updateById(byId);
        return "redirect:/book/listWorkerBook";
    }
}
